//
//  DownloadViewController.m
//  Hayate
//
//  Created by Holui on 11-12-9.
//  Copyright 2014 Holui. All rights reserved.
//

#import "DownloadViewController.h"
#import "FileSizeFormatHelper.h"
#import "FilePathHelper.h"
#import "FileTypeIcon.h"
#import "GEDateFromatter.h"
#import "DownLoadHelper.h"
#import "GEQLPreviewController.h"

@implementation DownloadViewController

@synthesize downloadingTable;
@synthesize downingList;
@synthesize finishedList;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = @"下载管理";
        
        //创建一个右边按钮
        UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"编辑"
                                                                        style:UIBarButtonItemStyleDone target:self
                                                                       action:@selector(editButtonEvent:)];
        self.navigationItem.rightBarButtonItem = rightButton;
    }
    return self;
}

- (void)editButtonEvent:(id)sender
{
    [downloadingTable setEditing:!downloadingTable.isEditing animated:YES];
    if (downloadingTable.isEditing) {
        self.navigationItem.rightBarButtonItem.title = @"完成";
    } else {
        self.navigationItem.rightBarButtonItem.title = @"编辑";
    }
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}


#pragma mark - View lifecycle

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    DownLoadHelper *downLoadHelper = [DownLoadHelper sharedInstance];
    downLoadHelper.downloadDelegate = self;
    self.downingList = downLoadHelper.downinglist;
    self.finishedList = downLoadHelper.finishedlist;
    [self.downloadingTable reloadData];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.downloadingTable.tableFooterView = [[UIView alloc] init];
    [self.downloadingTable registerClass:[DownloadCell class] forCellReuseIdentifier:@"DownloadCell"];
    [self.downloadingTable registerClass:[FinishedCell class] forCellReuseIdentifier:@"FinishedCell"];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.downloadingTable=nil;
}

#pragma mark -表格数据源
#pragma mark UITableViewDataSource

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
    if (sectionTitle == nil) return  nil;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, SuperWidth - 10, 29.5)];
    lable.textColor = [UIColor darkGrayColor];
    lable.font = [UIFont boldSystemFontOfSize:15];
    
    lable.text = sectionTitle;
    [view addSubview:lable];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 29.5, SuperWidth, 0.5)];
    lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.15];
    [view addSubview:lineView];
    
    return view;
}

//每个section显示的标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    switch (section) {
        case 0:
        {
            NSMutableString *newString = [[NSMutableString alloc] init];
            [newString appendString:@"正在下载"];
            [newString appendString:@" ("];
            [newString appendString:[[NSString alloc] initWithFormat:@"%lu",(unsigned long)downingList.count]];
            [newString appendString:@")"];
            return newString;
        }
        case 1:
        {
            NSMutableString *newString = [[NSMutableString alloc] init];
            [newString appendString:@"已下载"];
            [newString appendString:@" ("];
            [newString appendString:[[NSString alloc] initWithFormat:@"%lu",(unsigned long)finishedList.count]];
            [newString appendString:@")"];
            return newString;
        }
        default:
            return @"Unknown";
    }
}

//指定有多少个分区(Section)，默认为1
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;//返回标题数组中元素的个数来确定分区的个数
}


//指定每个分区中有多少行，默认为1
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {   
        case 0:
            return [self.downingList count];//每个分区通常对应不同的数组，返回其元素个数来确定分区的行数
            break;
        case 1:
            return [self.finishedList count];
            break;
        default:
            return 0;
            break;   
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //正在下载的文件列表
    if(indexPath.section == 0){
        static NSString *downCellIdentifier=@"DownloadCell";
        DownloadCell *cell=(DownloadCell *)[self.downloadingTable dequeueReusableCellWithIdentifier:downCellIdentifier];
        
        ASIHTTPRequest *theRequest=[self.downingList objectAtIndex:indexPath.row];
        FileAttributeModel *fileInfo=[theRequest.userInfo objectForKey:@"File"];
        cell.fileName.text=fileInfo.fileName;
        //cell.fileSize.text=fileInfo.fileSize;
        cell.fileInfo=fileInfo;
        cell.request=theRequest;
        //cell.fileCurrentSize.text=[FileSizeFormatHelper getFileSizeString:fileInfo.fileReceivedSize];
        
        //设置下载图片
        cell.fileIcon.image = [FileTypeIcon setFileTypeIcon:fileInfo.fileName];
        
        //设置下载进度
        double progressValue = [FileSizeFormatHelper getProgress:[FileSizeFormatHelper getFileSizeNumber:fileInfo.fileSize]
                            currentSize:[fileInfo.fileReceivedSize floatValue]];
        [cell.progress setProgress:progressValue];
        
        //设置下载大小及总大小
        NSMutableString *sizeStr = [[NSMutableString alloc] init];
        [sizeStr appendString:[FileSizeFormatHelper getFileSizeString:fileInfo.fileReceivedSize]];
        [sizeStr appendString:@"/"];
        [sizeStr appendString:fileInfo.fileSize];
        cell.fileCurrentSize.text = sizeStr;
        
        //文件正在下载
        if(fileInfo.isDownloading==YES){
            NSMutableString *sizeCurrent = [[NSMutableString alloc] initWithFormat:@"%.0f",progressValue*100];
            [sizeCurrent appendString:@"%"];
            cell.fileSize.text = sizeCurrent;
            [cell.operateIcon setImage:[UIImage imageNamed:@"btn_icon_paused.png"]];
            [cell.operateText setText:@"暂停"];
            
        } else {
            cell.fileSize.text = @"已暂停";
            [cell.operateIcon setImage:[UIImage imageNamed:@"btn_icon_download.png"]];
            [cell.operateText setText:@"继续"];
        }
        return cell;
    }
    
    //已完成下载的列表
    else if(indexPath.section == 1) {
        static NSString *finishedCellIdentifier=@"FinishedCell";
        FinishedCell *cell=(FinishedCell *)[self.downloadingTable dequeueReusableCellWithIdentifier:finishedCellIdentifier];
        
        FileAttributeModel *fileInfo=[self.finishedList objectAtIndex:indexPath.row];
        cell.fileNameLabel.text=fileInfo.fileName;
        cell.fileSizeLabel.text=fileInfo.fileSize;
        cell.fileInfo=fileInfo;
        cell.iconImage.image = [FileTypeIcon setFileTypeIcon:fileInfo.fileName];
        
        NSString *path = [[FilePathHelper getTargetFloderPath]stringByAppendingPathComponent:fileInfo.fileName];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSDictionary *fileAttributes = [fileManager fileAttributesAtPath:path traverseLink:YES];
        NSDate *modifeDate = [fileAttributes objectForKey:NSFileModificationDate];
        cell.fileTimeLabel.text = [GEDateFromatter formmatTimeDate:modifeDate];

        return cell;
    }
    
    return nil;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(editingStyle==UITableViewCellEditingStyleDelete)//点击了删除按钮,注意删除了该视图列表的信息后，还要更新UI和APPDelegate里的列表
    {
        NSFileManager *fileManager=[NSFileManager defaultManager];
        NSError *error;
        if(indexPath.section == 0)//正在下载的表格
        {
            ASIHTTPRequest *theRequest=[self.downingList objectAtIndex:indexPath.row];
            if([theRequest isExecuting])
            {
                [theRequest cancel];
            }
            FileAttributeModel *fileInfo=(FileAttributeModel*)[theRequest.userInfo objectForKey:@"File"];
            NSString *filePath=[[FilePathHelper getTempFolderPath] stringByAppendingPathComponent:fileInfo.fileName];
            NSString *path=[[FilePathHelper getTempFolderPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.temp",fileInfo.fileName]];
            NSInteger index=[fileInfo.fileName rangeOfString:@"."].location;
            NSString *name=[fileInfo.fileName substringToIndex:index];
            NSString *configPath=[[FilePathHelper getTempFolderPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.rtf",name]];
            [fileManager removeItemAtPath:filePath error:&error];
            [fileManager removeItemAtPath:path error:&error];
            [fileManager removeItemAtPath:configPath error:&error];
            if(!error)
            {
                NSLog(@"%@",[error description]);
            }
            [self.downingList removeObjectAtIndex:indexPath.row];
            [self.downloadingTable reloadData];
        }
        
        //已经完成下载的表格
        else if(indexPath.section == 1){
            FileAttributeModel *selectFile=[self.finishedList objectAtIndex:indexPath.row];
            NSString *path=[[FilePathHelper getTargetFloderPath]stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.temp",selectFile.fileName]];
            NSString *filePath=[[FilePathHelper getTargetFloderPath] stringByAppendingPathComponent:selectFile.fileName];
            
            [fileManager removeItemAtPath:path error:&error];
            [fileManager removeItemAtPath:filePath error:&error];
            if(!error) {
                NSLog(@"%@",[error description]);
            }
            [self.finishedList removeObject:selectFile];
            [self.downloadingTable reloadData];
        }
    }
}

-(void)updateCellOnMainThread:(FileAttributeModel *)fileInfo
{
    //改变列表进度
    for(id obj in self.downloadingTable.visibleCells)
    {
        if([obj isKindOfClass:[DownloadCell class]])
        {
            DownloadCell *cell=(DownloadCell *)obj;
            if(cell.fileInfo.fileURL == fileInfo.fileURL)
            {
                //cell.fileCurrentSize.text=[FileSizeFormatHelper getFileSizeString:fileInfo.fileReceivedSize];
                //[cell.progress setProgress:[FileSizeFormatHelper getProgress:[FileSizeFormatHelper getFileSizeNumber:fileInfo.fileSize] currentSize:[fileInfo.fileReceivedSize floatValue]]];
                
                //设置下载进度
                double progressValue = [FileSizeFormatHelper getProgress:[FileSizeFormatHelper getFileSizeNumber:fileInfo.fileSize]
                                                             currentSize:[fileInfo.fileReceivedSize floatValue]];
                [cell.progress setProgress:progressValue];
                NSMutableString *sizeCurrent = [[NSMutableString alloc] initWithFormat:@"%.0f",progressValue*100];
                [sizeCurrent appendString:@"%"];
                cell.fileSize.text = sizeCurrent;
                
                //设置下载大小及总大小
                NSMutableString *sizeStr = [[NSMutableString alloc] init];
                [sizeStr appendString:[FileSizeFormatHelper getFileSizeString:fileInfo.fileReceivedSize]];
                [sizeStr appendString:@"/"];
                [sizeStr appendString:fileInfo.fileSize];
                cell.fileCurrentSize.text = sizeStr;
            }
        }
    }
}


#pragma mark -
#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1) {
        FileAttributeModel *fileInfo=[self.finishedList objectAtIndex:indexPath.row];
        NSString *path = [[FilePathHelper getTargetFloderPath]stringByAppendingPathComponent:fileInfo.fileName];
        
        GEQLPreviewController *viewController = [[GEQLPreviewController alloc] initWithPathString:path];
        [self presentViewController:viewController animated:YES completion:nil];
    }
}


#pragma 下载更新界面的委托
#pragma mark DownloadDelegate

-(void)startDownload:(ASIHTTPRequest *)request;
{
    NSLog(@"-------开始下载!");
    [self.downloadingTable reloadData];
    
    //判断是否有新数据加入
//    MISCloudMainAppDelegate *appDelegate=[[UIApplication sharedApplication] delegate];
//    self.downingList = appDelegate.downLoadFile.downinglist;
//    self.finishedList = appDelegate.downLoadFile.finishedlist;
}

-(void)updateCellProgress:(ASIHTTPRequest *)request;
{
    FileAttributeModel *fileInfo=[request.userInfo objectForKey:@"File"];
    [self performSelectorOnMainThread:@selector(updateCellOnMainThread:) withObject:fileInfo waitUntilDone:YES];
}

-(void)failedDownload:(ASIHTTPRequest *)request error:(NSError*)error
{
    NSLog(@"-------下载失败!");
    [self.downloadingTable reloadData];
}

-(void)finishedDownload:(ASIHTTPRequest *)request;
{
    FileAttributeModel *fileInfo=[request.userInfo objectForKey:@"File"];
    [self.downingList removeObject:request];
    [self.finishedList addObject:fileInfo];
    [self.downloadingTable reloadData];
}


@end
